package com.pactera.madp.cp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.admin.api.constant.CrmDictTypeConstants;
import com.pactera.madp.admin.api.entity.SysDictItem;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.common.data.tenant.TenantContextHolder;
import com.pactera.madp.cp.api.dto.AddCustomerExcelDTO;
import com.pactera.madp.cp.api.dto.AddCustomerQueryDTO;
import com.pactera.madp.cp.api.entity.*;
import com.pactera.madp.cp.api.entity.crm.WorkCustomInfoEntity;
import com.pactera.madp.cp.api.feign.RemoteDeptService;
import com.pactera.madp.cp.api.feign.RemoteDictService;
import com.pactera.madp.cp.api.model.workcontacttag.GetEmployeeTagModel;
import com.pactera.madp.cp.api.vo.AddCustomerStatisticsVO;
import com.pactera.madp.cp.api.vo.AddCustomerVO;
import com.pactera.madp.cp.api.vo.DistributedCustomerVO;
import com.pactera.madp.cp.common.util.DataHandleUtil;
import com.pactera.madp.cp.common.util.PageUtil;
import com.pactera.madp.cp.common.util.ValidatorUtil;
import com.pactera.madp.cp.common.util.WxApiUtils;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.AddCustomerMapper;
import com.pactera.madp.cp.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Header;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * (CpAddCustomer)表服务实现类
 *
 * @author yushen.qi
 * @since 2022-01-11 18:17:23
 */
@Service("addCustomerService")
@Slf4j
public class AddCustomerServiceImpl extends ServiceImpl<AddCustomerMapper, AddCustomerEntity> implements AddCustomerService {

    static  String Custom_Add_URL = "https://cp.zyue27.com/#/custormerList?employeeId={}&id={}";

    /**
     * 企业
     */
    @Autowired
    private ICorpService corpService;

    @Autowired
    private IWorkDeptService workDeptService;

    @Autowired
    private IWorkEmployeeService workEmployeeService;

    @Autowired
    private IWorkContactEmployeeService workContactEmployeeService;

    @Autowired
    private WorkCustomInfoService workCustomInfoService;

    @Autowired
    private RemoteDeptService remoteDeptService;

    @Autowired
    private WorkAssetsInfoService workAssetsInfoService;

    @Autowired
    private RemoteDictService remoteDictService;

    @Override
    public Page<AddCustomerVO> getListPage(Page page) {
        List<AddCustomerVO> vo =(List<AddCustomerVO>) page(page, Wrappers.<AddCustomerEntity>lambdaQuery().eq(AddCustomerEntity::getCorpId,CorpContextHolder.getCorpId()).orderByDesc(BaseEntity::getCreateTime))
                .getRecords().stream().map(entity -> {
                    AddCustomerVO addCustomerVO = new AddCustomerVO();
                    BeanUtil.copyProperties(entity, addCustomerVO);
                    return addCustomerVO;
                }).collect(Collectors.toList());
        page.setRecords(vo);
        return page;
    }

    @Override
    public void toEmployee() {
        List<String> employeeIds = listObjs(Wrappers.<AddCustomerEntity>lambdaQuery()
                .select(AddCustomerEntity::getEmployeeId)
                .eq(AddCustomerEntity::getCorpId, CorpContextHolder.getCorpId())
                .eq(AddCustomerEntity::getState, 1), Object::toString).stream().distinct().collect(Collectors.toList());
        for (String employeeId : employeeIds) {
            List<AddCustomerEntity> list = list(Wrappers.<AddCustomerEntity>lambdaQuery().eq(AddCustomerEntity::getEmployeeId, employeeId).eq(AddCustomerEntity::getCorpId,CorpContextHolder.getCorpId()).eq(AddCustomerEntity::getState, 1));
            if (list.size()>0){
                //获取发送应用id
                Integer corpId = CorpContextHolder.getCorpId();
                String wxCorpId = corpService.getById(corpId).getWxCorpId();
                String textOne = "【请添加以下客户为你的个人客户】"+"\n";
                HashMap<String, Object> hashMap = new HashMap<>(1);
                StringBuilder stringBuilder = new StringBuilder();
                hashMap.put("content",stringBuilder);
                stringBuilder.append(textOne);
                for (int i = 0; i < list.size(); i++) {
                    AddCustomerEntity entity = list.get(i);
                    String textTwo =  "姓名：{}"+"&nbsp;&nbsp;"+" 手机号：{}" +"&nbsp;&nbsp;"+"<a href='"+StrUtil.format(Custom_Add_URL,entity.getEmployeeId(),entity.getId())  +"'>【确认添加】</a>";
                    String format = StrUtil.format(textTwo, entity.getContactName(), entity.getPhone());
                    stringBuilder.append(format);
                    if(i<list.size()-1){
                        stringBuilder.append("\n");
                    }
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("touser",employeeId);
                jsonObject.put("msgtype","text");
                jsonObject.put("agentid", corpService.getWxSendMsgAgentIdByWxCorpId(wxCorpId));
                jsonObject.put("text",hashMap);
                String s = jsonObject.toString();
                WxApiUtils.sendMsgToEmployeeByString(s,corpId,wxCorpId);
            }
        }
    }

    @Override
    public void toEmployeeOne(String employeeId, Integer id) {
        //获取发送应用id
        Integer corpId = CorpContextHolder.getCorpId();
        String wxCorpId = corpService.getById(corpId).getWxCorpId();
        AddCustomerEntity one = getOne(Wrappers.<AddCustomerEntity>lambdaQuery().eq(AddCustomerEntity::getEmployeeId, employeeId).eq(AddCustomerEntity::getId, id).eq(AddCustomerEntity::getCorpId, CorpContextHolder.getCorpId()));
        if(one==null){
            throw new CheckedException("通知失败！");
        }
        if("2".equals(one.getState())){
            throw new CheckedException("该客户已被添加！");
        }
        String textOne = "【请添加以下客户为你的个人客户】"+"\n";
        HashMap<String, Object> hashMap = new HashMap<>(1);
        StringBuilder stringBuilder = new StringBuilder();
        hashMap.put("content",stringBuilder);
        stringBuilder.append(textOne);
        String textTwo =  "姓名：{}"+"&nbsp;&nbsp;&nbsp;"+" 手机号：{}" +"&nbsp;&nbsp;&nbsp;"+"<a href='"+StrUtil.format(Custom_Add_URL,one.getEmployeeId(),one.getId())  +"'>【确认添加】</a>";
        String format = StrUtil.format(textTwo, one.getContactName(), one.getPhone());
        stringBuilder.append(format);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser",employeeId);
        jsonObject.put("msgtype","text");
        jsonObject.put("agentid", corpService.getWxSendMsgAgentIdByWxCorpId(wxCorpId));
        jsonObject.put("text",hashMap);
        String s = jsonObject.toString();
        WxApiUtils.sendMsgToEmployeeByString(s,corpId,wxCorpId);
    }

//    @Override
//    public IPage<AddCustomerVO> getCrmCustPage(Page page, AddCustomerQueryDTO dto) {
//        //企业下成员微信id列表
//        List<String> wxUserIds = workEmployeeService.listObjs(new QueryWrapper<WorkEmployeeEntity>()
//                .select("wx_user_id")
//                .eq("corp_id",CorpContextHolder.getCorpId()),o -> o.toString());
//        if (wxUserIds.isEmpty()) {
//            //避免为空in查询报错
//            wxUserIds.add("");
//        }
//        Page<AddCustomerVO> resultPage = workCustomInfoService.getAddCustomerVOPage(page, dto.getState(),wxUserIds);
//        resultPage.getRecords().forEach(vo->{
//            switch (vo.getSex()) {
//                case "20740001":
//                    vo.setSex("1");
//                    break;
//                case "20740002":
//                    vo.setSex("2");
//                    break;
//            }
//            if (vo.getDataType().equals("2") && vo.getState().equals("3")) {
//                //手机号匹配外部联系人与成员关系表数据,获取添加时间、外部联系人id
//                WorkEmployeeEntity employee = workEmployeeService.getWorkEmployeeByCorpIdAndWxUserId(CorpContextHolder.getCorpId(), vo.getCustMgrNo());
//                List<WorkContactEmployeeEntity> contactEmployeeEntities = workContactEmployeeService.list(new LambdaQueryWrapper<WorkContactEmployeeEntity>()
//                        .eq(WorkContactEmployeeEntity::getCorpId, CorpContextHolder.getCorpId())
//                        .eq(WorkContactEmployeeEntity::getEmployeeId, employee.getId()));
//                List<WorkContactEmployeeEntity> relationCollect = contactEmployeeEntities.stream()
//                        .map(entity -> {
//                            entity.setRemarkMobiles(JSONArray.parseArray(entity.getRemarkMobiles()).isEmpty() ? "" : JSONArray.parseArray(entity.getRemarkMobiles()).get(0).toString());
//                            return entity;
//                        })
//                        .filter(l -> l.getRemarkMobiles().equals(vo.getPhone()))
//                        .sorted(Comparator.comparing(l -> l.getCreateTime()))
//                        .collect(Collectors.toList());
//                vo.setId(relationCollect.isEmpty()? null : relationCollect.get(0).getContactId());
//                vo.setAddTime(relationCollect.isEmpty() ? null : relationCollect.get(0).getCreateTime());
//            }
//        });
//        return resultPage;
//    }

    @Override
    public IPage<AddCustomerVO> getCrmCustPage(Page page, AddCustomerQueryDTO dto) {
        //企业下成员微信id列表
        List<String> wxUserIds = workEmployeeService.listObjs(new QueryWrapper<WorkEmployeeEntity>()
                .select("wx_user_id")
                .eq("corp_id",CorpContextHolder.getCorpId()),o -> o.toString());
        if (wxUserIds.isEmpty()) {
            //避免为空in查询报错
            wxUserIds.add("");
        }
        List<Map<String, Long>> countList = workCustomInfoService.count(dto.getState(), wxUserIds);
        Long count = 0L;
        for (Map<String, Long> map : countList) {
            count += map.get("num");
        }
        List<AddCustomerVO> resultList = new ArrayList<>();
        Integer tableSort = 0;
        Long limitStart = (page.getCurrent() - 1) * page.getSize();
        Long limitEnd = limitStart + page.getSize();
        Long size = page.getSize();
        for (Map<String, Long> map : countList) {
            Long nowCount = map.get("num");
            tableSort = map.get("sort").intValue();
            // 若需要查的表记录在当前分表中完全涵盖，直接查该分表
            if (limitEnd <= nowCount) {
                List list = workCustomInfoService.addCustomerVOList(dto.getState(), wxUserIds, tableSort, limitStart, size);
                resultList.addAll(list);
                break;
            } else {
                // 若当前分表不包含要查的表记录，去下一分表判断
                if (nowCount <= limitStart) {
                    limitStart -= nowCount;
                    limitEnd = limitStart + size;
                } else {
                    // 该情况为limitStart < nowCount < limitEnd，说明要查的记录跨表了，
                    // 先从当前分表查nowCount - limitStart条数据，然后去下一分表判断
                    List list = workCustomInfoService.addCustomerVOList(dto.getState(), wxUserIds, tableSort, limitStart, nowCount - limitStart);
                    resultList.addAll(list);
                    // 后面还需查的记录数为size - (nowCount - limitStart)
                    size = size - (nowCount - limitStart);
                    if (size == 0) {
                        break;
                    }
                    limitStart = 0L;
                    limitEnd = limitStart + size;
                }
            }
        }

        Page<AddCustomerVO> resultPage = PageUtil.split(resultList, (int) page.getCurrent(), (int) page.getSize(), count);

//        Page<AddCustomerVO> resultPage = workCustomInfoService.getAddCustomerVOPage(page, dto.getState(),wxUserIds);
        resultPage.getRecords().forEach(vo->{
            switch (vo.getSex()) {
                case "20740001":
                    vo.setSex("1");
                    break;
                case "20740002":
                    vo.setSex("2");
                    break;
            }
            if (vo.getDataType().equals("2") && vo.getState().equals("3")) {
                //手机号匹配外部联系人与成员关系表数据,获取添加时间、外部联系人id
                WorkEmployeeEntity employee = workEmployeeService.getWorkEmployeeByCorpIdAndWxUserId(CorpContextHolder.getCorpId(), vo.getCustMgrNo());
                List<WorkContactEmployeeEntity> contactEmployeeEntities = workContactEmployeeService.list(new LambdaQueryWrapper<WorkContactEmployeeEntity>()
                        .eq(WorkContactEmployeeEntity::getCorpId, CorpContextHolder.getCorpId())
                        .eq(WorkContactEmployeeEntity::getEmployeeId, employee.getId()));
                List<WorkContactEmployeeEntity> relationCollect = contactEmployeeEntities.stream()
                        .map(entity -> {
                            entity.setRemarkMobiles(JSONArray.parseArray(entity.getRemarkMobiles()).isEmpty() ? "" : JSONArray.parseArray(entity.getRemarkMobiles()).get(0).toString());
                            return entity;
                        })
                        .filter(l -> l.getRemarkMobiles().equals(vo.getPhone()))
                        .sorted(Comparator.comparing(l -> l.getCreateTime()))
                        .collect(Collectors.toList());
                vo.setId(relationCollect.isEmpty()? null : relationCollect.get(0).getContactId());
                vo.setAddTime(relationCollect.isEmpty() ? null : relationCollect.get(0).getCreateTime());
            }
        });
        return resultPage;
    }

    @Override
    public AddCustomerStatisticsVO getStatisticsData(List<String> orgCodes,List<String> wxUserIds,Set<Integer> employeeIds) {
        //企业成员备注的客户手机号列表(取备注的第一个手机号)
        List<String> mobiles = employeeIds.isEmpty() ? new ArrayList<String>() : workContactEmployeeService.list(new LambdaQueryWrapper<WorkContactEmployeeEntity>()
                .eq(WorkContactEmployeeEntity::getCorpId, CorpContextHolder.getCorpId())
                .in(WorkContactEmployeeEntity::getEmployeeId, employeeIds))
                .stream()
                .map(l -> {
                    String mobile = JSONArray.parseArray(l.getRemarkMobiles()).isEmpty() ? "" : JSONArray.parseArray(l.getRemarkMobiles()).get(0).toString();
                    return mobile; })
                .filter(mobile -> !mobile.equals(""))
                .distinct()
                .collect(Collectors.toList());

        //CRM客户总数
        Integer crmCustTotalCount = workCustomInfoService.countInOrgCodes(orgCodes);

        //分配客户数
        Integer distributedCount = wxUserIds.isEmpty() ? 0 : workCustomInfoService.countInOrgCodesAndMgrNos(orgCodes,wxUserIds);

        //未分配客户数
        Integer undistributedCount = crmCustTotalCount - distributedCount;

        //已添加客户数
        Integer addedCount = mobiles.isEmpty() ? 0 : workCustomInfoService.countInMobiles(mobiles);

        //添加完成率
        String addedPercentage = DataHandleUtil.division(addedCount,distributedCount);

        AddCustomerStatisticsVO vo = new AddCustomerStatisticsVO();
        vo.setCrmCustTotalCount(crmCustTotalCount);
        vo.setDistributedCount(distributedCount);
        vo.setUndistributedCount(undistributedCount);
        vo.setAddedCount(addedCount);
        vo.setAddedPercentage(addedPercentage);
        return vo;
    }

    @Override
    public AddCustomerStatisticsVO getStatisticsDatas(Integer deptId, Integer wxDeptId) {
        AddCustomerStatisticsVO vo;
        List<String> orgCodes = getOrgCodes(deptId);
        Map<String, Object> map = getEmployeeIdsAndWxUserIds(deptId);
        Set<Integer> employeeIds = (Set<Integer>)map.get("employeeIds");
        List<String> wxUserIds = (List<String>)map.get("wxUserIds");
        if (orgCodes == null || orgCodes.size() == 0) {
            vo = new AddCustomerStatisticsVO();
            vo.setCrmCustTotalCount(0);
            vo.setDistributedCount(0);
            vo.setUndistributedCount(0);
            vo.setAddedCount(0);
            vo.setAddedPercentage(DataHandleUtil.division(vo.getAddedCount(),vo.getDistributedCount()));
        } else {
            vo = getStatisticsData(orgCodes,wxUserIds,employeeIds);
        }
        WorkDeptEntity workDeptEntity = workDeptService.getOne(
                Wrappers.<WorkDeptEntity>lambdaQuery()
                        .eq(WorkDeptEntity::getWxDepartmentId, wxDeptId)
        );
        vo.setCode(String.valueOf(workDeptEntity.getWxDepartmentId()));
        vo.setName(workDeptEntity.getName());
        return vo;
    }

    private Map<String,Object> getEmployeeIdsAndWxUserIds(Integer deptId) {
        R r = remoteDeptService.getDeptsAndUsers(deptId);
        log.info("r:{}",r);
        Map<String, Object> data = (Map) r.getData();
        List<Integer> wxDeptIds = (List<Integer>) data.get("wxDeptIds");
        List<String> userMobiles = (List<String>) data.get("userMobiles");
        Set<Integer> employeeIds = workEmployeeService.getEmployeeIds(wxDeptIds, userMobiles);
        List<String> wxUserIds = employeeIds.isEmpty() ? new ArrayList<String>() : workEmployeeService.listByIds(employeeIds)
                .stream()
                .map(WorkEmployeeEntity::getWxUserId)
                .collect(Collectors.toList());
        HashMap<String, Object> map = new HashMap<>();
        map.put("employeeIds",employeeIds);
        map.put("wxUserIds",wxUserIds);
        return map;
    }

    private List<String> getOrgCodes(Integer deptId) {
        R r = remoteDeptService.getAllChildrenOrgCode(deptId);
        log.info("r:{}",r);
        List<String> orgCodes = (List<String>)r.getData();
        return orgCodes;
    }

    @Override
    public IPage<AddCustomerStatisticsVO> getStatisticsPage(Page page,Integer fenHangDeptId) {
        Integer corpId = CorpContextHolder.getCorpId();
        Integer tenantId = TenantContextHolder.getTenantId();
        ArrayList<AddCustomerStatisticsVO> vos = new ArrayList<>();
        List<WorkDeptEntity> deptList = new ArrayList<>();
        if (fenHangDeptId == null) {
            //所有分行机构集合
            deptList = workDeptService.list(new LambdaQueryWrapper<WorkDeptEntity>()
                    .eq(WorkDeptEntity::getTenantId, tenantId)
                    .eq(WorkDeptEntity::getCorpId, corpId).eq(WorkDeptEntity::getLevel, 1));

        } else {
            WorkDeptEntity dept = workDeptService.getById(fenHangDeptId);
            if (!dept.getLevel().equals(1)) {
                throw new IllegalArgumentException("查看详情的机构不属于分行！");
            }
            //所有支行机构集合
            deptList = workDeptService.list(new LambdaQueryWrapper<WorkDeptEntity>()
                    .eq(WorkDeptEntity::getTenantId, tenantId)
                    .eq(WorkDeptEntity::getCorpId, corpId).eq(WorkDeptEntity::getLevel, 2)
                    .eq(WorkDeptEntity::getParentId,fenHangDeptId));

        }

        deptList.forEach(d -> {
            List<Integer> allChildDepts = workDeptService.getAllChilds(d.getId());
            Integer crmCustTotalCount = baseMapper.getCountByDeptsAndState(allChildDepts, null);
            Integer addedCount = baseMapper.getCountByDeptsAndState(allChildDepts, "4");
            AddCustomerStatisticsVO vo = new AddCustomerStatisticsVO();
            vo.setCrmCustTotalCount(crmCustTotalCount);
            vo.setAddedCount(addedCount);
            vos.add(vo);
        });
        Page<AddCustomerStatisticsVO> split = PageUtil.split(vos, (int) page.getCurrent(), (int) page.getSize());
        return split;
    }

    @Override
    public List<AddCustomerEntity> getListByWxUserId(String wxUserId) {
        Integer corpId = CorpContextHolder.getCorpId();
        Integer tenantId = TenantContextHolder.getTenantId();
        List<AddCustomerEntity> list = this.list(new LambdaQueryWrapper<AddCustomerEntity>()
                .eq(AddCustomerEntity::getCorpId, corpId)
                .eq(AddCustomerEntity::getTenantId, tenantId)
                .eq(AddCustomerEntity::getEmployeeId, wxUserId));
        return list;

    }

    @Override
    public R inputCrmCustData(MultipartFile file) {
        Integer corpId = CorpContextHolder.getCorpId();
        Integer tenantId = TenantContextHolder.getTenantId();
        int j = 0;
        try {
            //将输入的文件转换为流对象
            InputStream inputStream = file.getInputStream();
            //将流对象转换为ExcelReader对象
            ExcelReader reader = ExcelUtil.getReader(inputStream,j);
            //将流对象转换为字符串
            String text = reader.getExtractor().getText();
            //将字符串通过"\n"切割
            String[] split = text.split("\n");
            String[] headers = split[1].split("\\t");
            if (!headers[0].equals("客户编号")) {
                throw new IllegalArgumentException("EXCEL格式不正确，请使用EXCEL模板导入");
            }
            if (!headers[1].equals("客户姓名")) {
                throw new IllegalArgumentException("EXCEL格式不正确，请使用EXCEL模板导入");
            }
            if (!headers[2].equals("客户性别")) {
                throw new IllegalArgumentException("EXCEL格式不正确，请使用EXCEL模板导入");
            }
            if (!headers[3].equals("客户手机号")) {
                throw new IllegalArgumentException("EXCEL格式不正确，请使用EXCEL模板导入");
            }
            if (!headers[4].equals("客户经理编号")) {
                throw new IllegalArgumentException("EXCEL格式不正确，请使用EXCEL模板导入");
            }
            if (!headers[5].equals("客户经理姓名")) {
                throw new IllegalArgumentException("EXCEL格式不正确，请使用EXCEL模板导入");
            }
            //将ExcelReader对象转换为List<Map>对象
            List<Map<String, Object>> maps = reader.readAll();
            AtomicInteger i = new AtomicInteger(2);
            maps.forEach(m->{
                String custNo = m.get("客户编号").toString();
                String custName = m.get("客户姓名").toString();
                String mobileTel = m.get("客户手机号").toString();
                String custMgrNo = m.get("客户经理编号").toString();
                String custMgrName = m.get("客户经理姓名").toString();
                if (StrUtil.isBlank(custNo)){
                    throw new NullPointerException("第"+i.get()+"行的客户编号不能为空");
                }
                if (StrUtil.isBlank(custName)){
                    throw new NullPointerException("第"+i.get()+"行的客户姓名不能为空");
                }
                if (StrUtil.isBlank(mobileTel)){
                    throw new NullPointerException("第"+i.get()+"行的客户手机号不能为空");
                } else if(!ValidatorUtil.isMobile(mobileTel)){
                    throw new IllegalArgumentException("第"+i.get()+"行的客户手机号格式不正确");
                }
                if (StrUtil.isBlank(custMgrNo)){
                    throw new NullPointerException("第"+i.get()+"行的客户经理编号不能为空");
                }
                if (StrUtil.isBlank(custMgrName)){
                    throw new NullPointerException("第"+i.get()+"行的客户经理姓名不能为空");
                }
                i.incrementAndGet();
            });

            List<String> wxUserIds = workEmployeeService.listObjs(new QueryWrapper<WorkEmployeeEntity>()
                    .select("wx_user_id")
                    .eq("corp_id",corpId),o -> o.toString());
            log.info("wxUserIds:{}",wxUserIds);
            List<WorkContactEmployeeEntity> contactEmployeeEntities = workContactEmployeeService.list(new QueryWrapper<WorkContactEmployeeEntity>().eq("corp_id", corpId));
            ArrayList<AddCustomerEntity> list = new ArrayList<>();
            maps.forEach(m->{
                AddCustomerEntity addCustomerEntity = new AddCustomerEntity();
                addCustomerEntity.setContactId(m.get("客户编号").toString());
                addCustomerEntity.setContactName(m.get("客户姓名").toString());
                addCustomerEntity.setPhone(m.get("客户手机号").toString());
                if (m.get("客户性别") == null) {
                    addCustomerEntity.setSex("");
                } else if (m.get("客户性别").toString().equals("男")) {
                    addCustomerEntity.setSex("1");
                } else if (m.get("客户性别").toString().equals("女")) {
                    addCustomerEntity.setSex("2");
                }
                addCustomerEntity.setEmployeeId(m.get("客户经理编号").toString());
                addCustomerEntity.setEmployeeName(m.get("客户经理姓名").toString());
                addCustomerEntity.setCorpId(corpId);
                addCustomerEntity.setTenantId(tenantId);
                log.info("导入的客户经理编号:{}",m.get("客户经理编号").toString());
                if (wxUserIds.contains(m.get("客户经理编号").toString())) {
                    addCustomerEntity.setState("1");
                } else {
                    addCustomerEntity.setState("2");
                }
                if (!contactEmployeeEntities.isEmpty()) {
                    for (WorkContactEmployeeEntity contactEmployeeEntity : contactEmployeeEntities) {
                        if (contactEmployeeEntity.getRemarkMobiles().contains(m.get("客户手机号").toString())) {
                            addCustomerEntity.setState("3");
                            addCustomerEntity.setAddTime(contactEmployeeEntity.getCreateTime());
                            break;
                        }
                    }
                }
                list.add(addCustomerEntity);
            });

            this.saveBatch(list);
        } catch (NullPointerException e) {
            e.printStackTrace();
            return R.failed(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok("导入成功");
    }

    @Override
    public void outputExcel(HttpServletResponse response, OutputStream out) {
        AddCustomerExcelDTO dto = new AddCustomerExcelDTO();
        LinkedList<Integer> department = new LinkedList<>();
        LinkedList<Integer> isLeaderInDept = new LinkedList<>();
        department.add(0,1);
        department.add(1,2);
        isLeaderInDept.add(0,1);
        isLeaderInDept.add(0,0);

        dto.setCustNo("1000000001");
        dto.setCustName("张三");
        dto.setSex("男");
        dto.setMobileTel("13888888888");
        dto.setCustMgrNo("1001000000");
        dto.setCustMgrName("王小二");

        List<AddCustomerExcelDTO> rows = CollUtil.newArrayList(dto);
        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(true);

        writer.addHeaderAlias("custNo","客户编号");
        writer.addHeaderAlias("custName","客户姓名");
        writer.addHeaderAlias("sex","客户性别");
        writer.addHeaderAlias("mobileTel","客户手机号");
        writer.addHeaderAlias("custMgrNo","客户经理编号");
        writer.addHeaderAlias("custMgrName","客户经理姓名");

        // 设置列宽
        writer.setColumnWidth(0,20);
        writer.setColumnWidth(1,20);
        writer.setColumnWidth(2,20);
        writer.setColumnWidth(3,20);
        writer.setColumnWidth(4,20);
        writer.setColumnWidth(5,20);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=crm_cust_data_example.xlsx");

        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();

        IoUtil.close(out);
    }

    @Override
    public IPage<DistributedCustomerVO> getDistributedCustPage(Page page, String wxUserId,String name) {
        //crm客户字典
        List<SysDictItem> crmDictList = remoteDictService.getCrmCustDict();

        //企业下成员微信id列表
        List<String> wxUserIds = workEmployeeService.listObjs(new QueryWrapper<WorkEmployeeEntity>()
                .select("wx_user_id")
                .eq("corp_id",CorpContextHolder.getCorpId()),o -> o.toString());
        if (wxUserIds.isEmpty()) {
            //避免为空in查询报错
            wxUserIds.add("");
        }

        //潜在客户列表
        List<AddCustomerVO> resultList = workCustomInfoService.getAddCustomerVOListByCustMgrNo(wxUserId,wxUserIds);
        ArrayList<DistributedCustomerVO> vos = new ArrayList<>();
        resultList.forEach(l->{
            switch (l.getSex()) {
                case "20740001":
                    l.setSex("1");
                    break;
                case "20740002":
                    l.setSex("2");
                    break;
            }
            DistributedCustomerVO vo = new DistributedCustomerVO();
            vo.setCustNo(l.getCustNo());
            vo.setMobile(l.getPhone());
            vo.setName(l.getName());
            vo.setCustAum("");
            vo.setAssetsLevel(valueToText(l.getAssetsLevel(), CrmDictTypeConstants.TYPE_ASSETS_LEVEL,crmDictList));
            vos.add(vo);
        });

        List<String> custNos = vos.stream().map(vo -> vo.getCustNo()).collect(Collectors.toList());
        if (!custNos.isEmpty()) {
            List<Map<String, Object>> mapList = workAssetsInfoService.listInCustNos(custNos);
            vos.forEach(vo->{
                if (mapList.isEmpty()) {
                    vo.setCustAum("");
                } else {
                    mapList.forEach(map->{
                        if (map.get("custNo").equals(vo.getCustNo())) {
                            vo.setCustAum(map.get("aumBal") == null ? ""  : map.get("aumBal").toString());
                        }
                    });
                }
            });
        }
        Page<DistributedCustomerVO> resultPage = new Page<>();
        if (!StrUtil.isBlank(name)) {
            List<DistributedCustomerVO> results = vos.stream()
                    .filter(vo -> vo.getName().contains(name) || vo.getCustNo().equals(name) || vo.getMobile().equals(name))
                    .sorted(Comparator.comparing(DistributedCustomerVO::getCustAum).reversed())
                    .collect(Collectors.toList());
            results.forEach(r->{
                r.setCustAum("");
            });
            resultPage = PageUtil.split(results, (int) page.getCurrent(), (int) page.getSize());
            return resultPage;
        } else {
            vos.sort(Comparator.comparing(DistributedCustomerVO::getCustAum).reversed());
            //排完序清除敏感数据
            vos.forEach(vo->{
                vo.setCustAum("");
            });

            resultPage = PageUtil.split(vos, (int) page.getCurrent(), (int) page.getSize());
            return resultPage;
        }
    }


    private String valueToText(String dictValue, String dictType, List<SysDictItem> crmDictList) {
        List<String> textList = crmDictList.stream()
                .filter(l -> l.getType().equals(dictType) && l.getValue().equals(dictValue))
                .map(l->l.getLabel())
                .collect(Collectors.toList());
        if (textList.isEmpty()) {
            return dictValue;
        } else {
            return textList.get(0);
        }
    }
}
